package com.changeover.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.changeover.dao.IUserDao;
import com.changeover.gwt.shared.model.User;

@Repository
public class UserDao extends AbstractDao<User> implements IUserDao {

//    @Autowired
    private SessionFactory sessionFactory;

    @Transactional(readOnly=true)
    public User get(String username, String password) {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("from User where name = :name and passwd = :passwd ");
        query.setParameter("name", username);
        query.setParameter("passwd", password);
        @SuppressWarnings("unchecked")
        List<User> list = query.list();
        if (list.size() > 1) {
            throw new IllegalStateException("More then one user!");
        }
        return list.size() > 0 ? list.get(0) : null;
    }
    
    @Transactional(readOnly=true)
    @SuppressWarnings("unchecked")
    public User getUser(String username) {
        Session session = sessionFactory.getCurrentSession();
        Query q = session.createQuery("from User where name=:name");
        q.setParameter("name", username);
        List<User> users = q.list();
        
        return users.size() > 0 ? users.get(0): null;
    }

    protected Class<User> getEntityClass() {
        return User.class;
    }

}
